package com.pat.miniloyalty;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.log.Log;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class CalculateServlet extends HttpServlet
{
	protected final static Logger m_log = Logger.getLogger(CalculateServlet.class.getName());
	
	/**
	 * Calculates user statistic by UID and CID. Should be full form
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		// User ID from request
		final String uid = req.getParameter("uid");
		// Company ID from request
		final String companyId = req.getParameter("cid");
		
		// TODO: validate UID and CID for calculate

		//String query = "select from " + TranData.class.getName();// + " where uid = " + uid;
		PersistenceManager pm = LoyaltyPmf.get().getPersistenceManager();
		Query query = pm.newQuery(TranData.class);
		query.setFilter("uid == uidParam");
		query.declareParameters("String uidParam");
		
		try
		{
			List<TranData> list = (List<TranData>) query.execute(uid);
			if( list.iterator().hasNext() )
			{
				for( TranData purchase : list )
				{
					resp.getWriter().write("ID: " + "UID: " + purchase.getUid() + ", sum: " + purchase.getSumInMinorCurrency() + " at: " + purchase.getCreatedAt() + System.getProperty("line.separator"));
				}
			}else
			{
				resp.getWriter().write("Client: " + uid + " has no records for company: " + companyId);
			}
		} catch (Exception ex)
		{
			ex.printStackTrace();
		}finally
		{
			query.closeAll();
		}
	}
	
	public void doPost( HttpServletRequest req, HttpServletResponse resp ) throws IOException
	{
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		if( user == null )
		{
			resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
		}
		
		// Got User ID from request
		final String uid = req.getParameter("uid");
		if( uid.length() < 3 )
		{
			m_log.warning("Specified UID [" + uid + "] is too short!");
			resp.sendRedirect("/");
		}
		
		resp.setContentType("text/plain");
		m_log.info("Calculating totals, UID is [" + uid + "], company is [" + userService.getCurrentUser().getUserId() + "]");

		String query = "SELECT from " + TranData.class.getName();
		PersistenceManager pm = LoyaltyPmf.get().getPersistenceManager();
		List<TranData> list = (List<TranData>) pm.newQuery(query).execute();

		StringBuffer sb = new StringBuffer();
		int discount = 0;
		if( list.isEmpty() )
		{
			m_log.info("UID [" + uid + "] has no purchase for company [" + user.getUserId() + "]");
		}else
		{
			resp.getWriter().println("UID\t\t\t\tCompany ID\t\t\t\tSum");
			for( TranData t : list )
			{
				sb.append(t.getUid() + "\t\t\t" + t.getCompany().getUserId() + "\t\t" + t.getSumInMinorCurrency() + System.getProperty("line.separator"));
				discount += t.getSumInMinorCurrency();
			}
			resp.getWriter().println(sb.toString());
		}

		resp.getWriter().println("Discount for [" + uid + "] is: " + discount + "Lt");

//		if( this.addPurchase(uid, user, 10) )
//		{
//			m_log.info("Redirecting to main page...");
////			resp.sendRedirect("/");
//		}else
//		{
//			m_log.warning("Error calculating");
//			resp.getWriter().println("Error saving totals...");
//			//resp.sendError(, "Error calculating totals!");
//		}
	}
	
	/**
	 * Saves transaction in DB
	 * @param uid - unique ID of customer 
	 * @param company company object, serving customes
	 * @param sum sum of purchase in minor currency
	 * @return whether transaction was saved
	 */
	protected boolean addPurchase( String uid, User company, int sum )
	{
		boolean isOk = false;
		
		m_log.info("Adding purchase to company [" + company.getUserId() + "]");
		TranData data = new TranData(uid, company, sum);
		PersistenceManager pm = LoyaltyPmf.get().getPersistenceManager();
		
		try
		{
			pm.makePersistent(data);
			m_log.info("Total are saved OK...");
			isOk = true;
		}catch( Exception ex )
		{
			m_log.warning("Error saving data!");
			m_log.warning(ex.toString());
		}
		
		return isOk;
	}
}
